package com.nc.dao.impl;

import com.nc.bean.Person;
import com.nc.dao.PersonDao;
import com.nc.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @create 2020-08-04 19:02
 * @desc 名人接口实现类
 **/
public class PersonDaoImpl implements PersonDao {

    /**
     * 查询所有数据
     * @return
     */
    @Override
    public List<Person> queryAll(String name) {
        List<Person> list = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection conn = DBUtil.getConnection();
        String sql = "select * from person where name like ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,"%"+name+"%");
            rs = ps.executeQuery();
            while (rs.next()){
                Person person = new Person();
                person.setId(rs.getInt("id"));
                person.setName(rs.getString("name"));
                person.setSex(rs.getInt("sex"));
                person.setHeadUrl(rs.getString("headUrl"));
                person.setProfession(rs.getString("profession"));
                person.setIntroduce(rs.getString("introduce"));
                person.setCreatedTime(rs.getDate("createdTime"));
                person.setUpdatedTime(rs.getDate("updatedTime"));
                list.add(person);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(rs,ps,conn);
        }
        return list;
    }

    @Override
    public List<Person> queryBySex(String sex,String name) {
        List<Person> list = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection conn = DBUtil.getConnection();
        String str = sex==null?"":" and sex="+sex;
        String sql = "select * from person where name like ?"+str;
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,"%"+name+"%");
            rs = ps.executeQuery();
            while (rs.next()){
                Person person = new Person();
                person.setId(rs.getInt("id"));
                person.setName(rs.getString("name"));
                person.setSex(rs.getInt("sex"));
                person.setHeadUrl(rs.getString("headUrl"));
                person.setProfession(rs.getString("profession"));
                person.setIntroduce(rs.getString("introduce"));
                person.setCreatedTime(rs.getDate("createdTime"));
                person.setUpdatedTime(rs.getDate("updatedTime"));
                list.add(person);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(rs,ps,conn);
        }
        return list;
    }
}
